<?php
class ApiRebuilder {
	private $dir;
	public function __construct ($config) {
		$this->dir = $config['dir'];
		$this->config = $config;
	}
	public function rebuild () {
		$config = $this->config;
		$dir = realpath($this->dir);
		$items = scandir($dir);
		$items = array_filter($items, function ($item) use ($dir) {
			if(is_file($dir.'/'.$item)) {
				return true;
			}
		});
		$items = array_map(function ($item) use ($dir, $config) {
			$apiItem = new ApiItem($config['Item'], $dir.'/'.$item);
			$apiItem->rebuild();
			return $apiItem;
		}, $items);
	}
}
class ApiItem {
	private $path;
	private $content;
	private $operInit;
	private $factoryWrapper;
	private $smallLetterName;
	private $bigLetterName;
	private $info;
	public function __construct ($config, $path) {
		$this->path = realpath($path);
		$this->info = pathinfo($this->path);
		$this->setValues($config);
		$this->getContent();
		$this->setNames();
	}
	public function rebuild () {
		$this->setOperValue();
		$this->wrapInFactory();
		$this->saveChanges();
		$this->rename();
	}
	private function setValues ($arr) {
		foreach ($arr as $key => $value) {
			$this->{$key} = $value;
		}
	}
	private function setNames () {
		$sln = $this->info['filename'];
		$bln = $this->info['filename'];
		$bln[0] = strtoupper($bln[0]);
		$this->smallLetterName = $sln;
		$this->bigLetterName = $bln;
	}
	private function saveChanges () {
		file_put_contents($this->path, $this->content);
	}
	private function getContent () {
		$this->content = file_get_contents($this->path);
	}
	private function rename () {
		$dir = dirname($this->path);
		$ext = $this->info['extension'];
		$oldName = $dir.'/'.$this->smallLetterName.'.'.$ext;
		$newName = $dir.'/'.$this->bigLetterName.'.'.$ext;
		rename($oldName, $newName);
		//print_r($newName);
		$this->path = $newName;
	}
	private function setOperValue () {
		$this->content = str_replace($this->operInit, $this->operInit.' = \''.$this->smallLetterName.'\'', $this->content);
	}
	private function wrapInFactory () {
		$this->content = sprintf($this->factoryWrapper, $this->bigLetterName, $this->content, $this->smallLetterName);
	}
}
$rebuilder = new ApiRebuilder(array(
	'dir' => __DIR__.'/../js/Api',
	'Item' => array(
		'factoryWrapper' => 'App.Api.factory(\'Api.%s\', [function () {
			%s
			return %s;
		}]);',
		'operInit' => 'var oper'
	)
));
$rebuilder->rebuild();
?>